<template>
  <view class="notice" ref="noticeRef">
    <view
      class="message" :class="`${item.type} ${item.mid}`"
      v-for="item in notices" :key="item._name" ref="msg"
    >
      <view class="content">{{ item.content }}</view>
    </view>
  </view>
</template>

<script>
  // 默认选项
  const DefaultOptions = {
    duration: 1500,
    type: "primary",
    content: "这是一条提示信息！"
  };

  let mid = 0;

  export default {
    data() {
      return {
        notices: []
      };
    },
    methods: {
      add(notice = {}) {
        // name标识 用于移除弹窗
        let _name = this.getName();
        // 合并选项
        notice = Object.assign(
          {
            _name,
            mid: `mid${mid}`
          },
          DefaultOptions,
          notice
        );

        this.notices.push(notice);

        setTimeout(() => {
          this.removeNotice(_name);
        }, notice.duration);
      },
      getName() {
        return "msg_" + mid++;
      },
      removeNotice(_name) {
        let index = this.notices.findIndex(item => item._name === _name);
        this.notices.splice(index, 1);
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import  './index.scss';
</style>